package js.web.center.netty.client;

import org.apache.log4j.Logger;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;
import js.web.center.netty.client.iface.IJsWebClientSDK;
import js.web.center.netty.entity.JsWebSocketBaseProtocol;

public class JsWebClientHandler extends ChannelInboundHandlerAdapter {
	private Logger logger=Logger.getLogger(JsWebClientHandler.class);
	private ChannelHandlerContext ctx;
	private IJsWebClientSDK clientSDK;
	public JsWebClientHandler(IJsWebClientSDK clientSDK) {
		this.clientSDK=clientSDK;
	}
	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		
	}
	public void sendMsg(byte[] bytes){
		JsWebSocketBaseProtocol baseProtocol=new JsWebSocketBaseProtocol(bytes.length, bytes);
		ctx.writeAndFlush(baseProtocol);
	}
	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		this.clientSDK.active(ctx);
	}
	@Override
	public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
		this.clientSDK.open(ctx);
	}
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		try{
			this.clientSDK.receive(ctx, msg);
//			JsWebSocketBaseProtocol baseProtocol=(JsWebSocketBaseProtocol) msg;
//			logger.debug(baseProtocol);
		}catch(Exception e){
			logger.error(e);
		}finally {
			ReferenceCountUtil.release(msg);
		}
	}
	@Override
	public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
		this.clientSDK.close(ctx);
	}
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		ctx.close();
	}
}
